using UnityEngine;
using QFramework;
using System.Collections.Generic;
using System.Collections;

// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间
// 2.命名空间更改后，生成代码之后，需要把逻辑代码文件（非 Designer）的命名空间手动更改
namespace QFramework.Example
{

    public enum CopyItemState
    {
        Run,
        Remove
    }

	public partial class CopyItem : ViewController,ISkill,IController,ICanReadModels
	{
        public string SkillName => "偏转护盾";

        public bool IsUnLocked { get ; set; }


        CopyItemState copyItemState = CopyItemState.Run;

        public void CallBack()
        {
            //throw new System.NotImplementedException();
        }


        [SerializeField]
        List<Collider2D> SwordList = new List<Collider2D>();

        /// <summary>
        /// 该技能的运行时间
        /// </summary>
        public float runTime = 0;

        /// <summary>
        /// 该技能的冷却时间
        /// </summary>
        public float removeTime = 0;



        public bool isRun = true;
        public bool isRemove = false;
      
        public IArchitecture GetArchitecture()
        {
			return Global.Interface;
		}

        public void ReadModels()
        {
            //Sliend.OnTriggerEnter2DEvent(collider =>
            //{

            //    var hitbox = collider.GetComponent<HitHurtBox>();
            //    if (hitbox != null)
            //    {
            //        if (hitbox.CompareTag("Enemy"))
            //        {

            //        }
            //    }

            //}).UnRegisterWhenGameObjectDestroyed(gameObject);



            DataManager.Instance.copyItemModel.AbilityItemCount.RegisterWithInitValue(value =>
            {

                //var currentCount = value;

                var addCount = value; /*- SwordList.Count;*/

                for (int i = 0; i < addCount; i++)
                {
                    SwordList.Add(Sliend.InstantiateWithParent(this).Show().Self(self =>
                    {
                        self.OnTriggerEnter2DEvent(value =>
                        {
                            var onow = value.GetComponent<HitHurtBox>();
                            if (onow)
                            {
                                if (onow.Owner.CompareTag("Enemy"))
                                {
                                    var enemys = onow.Owner.GetComponent<EnemyFathers>();

                                    if (enemys is IEnemy enemy)
                                    {
                                        //Debug.Log("实现了Ienemy接口");
                                        //enemys.Hurt(simpleCircleModel.SimpleCircleDamage);
                                        DamageSystem.SetDamage(DataManager.Instance.copyItemModel.AbilityDamage.Value, enemys);
                                        ///击退逻辑
                                        //if (Random.Range(0, 1f) < 0.5f)
                                        //{
                                        //    value.attachedRigidbody.velocity =
                                        //    value.NormalizedDirection2DFrom(self) * 5
                                        //    + value.NormalizedDirection2DFrom(Player.Instance) * 10;
                                        //}
                                    }


                                }
                            }
                        }).UnRegisterWhenGameObjectDestroyed(self);
                    }));
                }
                UpDateSirclePos();

            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        public void RemoveCallBack()
        {
            //throw new System.NotImplementedException();
        }

        void Start()
		{
            // Code Here

            ReadModels();
            CopyStateSet_Remove();
            CopyStateSet_Run();
            UpDateSirclePosState();
            UpDateSirclePos();
        }

        private void Update()
        {
            var degree = Time.frameCount * DataManager.Instance.copyItemModel.AbilityItemSpeed.Value;
            this.LocalEulerAnglesZ(-degree);
        }


        void UpDateSirclePosState()
        {

            switch (copyItemState)
            {
                case CopyItemState.Run:
                    StartCoroutine(SetItemActive(true));
                    
                    break;
                case CopyItemState.Remove:
                   
                    StartCoroutine(SetItemActive(false));
                    break;
            }
        }



        void CopyStateSet_Remove()
        {
            if (isRun)
            {
                runTime += Time.deltaTime;
                if (runTime >= DataManager.Instance.copyItemModel.AbilityRunTime.Value)
                {
                    removeTime = 0;
                    isRun = false;
                    isRemove = true;
                    copyItemState = CopyItemState.Remove;
                    Debug.Log("护盾冷却");
                }
            }
              
           
        }

        void CopyStateSet_Run()
        {
            if (isRemove)
            {
                removeTime += Time.deltaTime;
                if (removeTime >= DataManager.Instance.copyItemModel.AbilityAtkTime.Value)
                {
                    runTime = 0;
                    isRun = true;
                    isRemove = false;
                    copyItemState = CopyItemState.Run;
                    Debug.Log("护盾激活");
                }
            }

           
        }



        void UpDateSirclePos()
        {
            StartCoroutine(SetItemActive(true));
            runTime = 0;

            var degree = Time.frameCount;

            var durationDegress = 360 / SwordList.Count;
            for (int i = 0; i < SwordList.Count; i++)
            {

                var circleLocalPos =
               new Vector2(Mathf.Cos(durationDegress * i * Mathf.Deg2Rad),
               Mathf.Sin(durationDegress * i *
               Mathf.Deg2Rad)) * DataManager.Instance.copyItemModel.AbilityRadius.Value * DataManager.Instance.copyItemModel.AbilityItemSpeed.Value;



                SwordList[i].LocalPosition(circleLocalPos.x, circleLocalPos.y);

                SwordList[i].LocalEulerAnglesZ(durationDegress * i - 90);
            }
        }

        IEnumerator SetItemActive(bool isRun)
        {

            foreach (var item in SwordList)
            {
                item.gameObject.SetActive(isRun);
            }
            yield return null;
        }


    }
}
